package org.jeecg.modules.sggg.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginMember;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.ToolUtils;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping("/applets/")
@Api(tags = "小程序中的一些接口")
public class AppletsController {

    private final ISysDictService sysDictService;

    private final ToolUtils toolUtils;

    @Autowired
    // 居民管理
    private ISgMemberService sgMemberService;

    // 血压记录表
    private final ISgBlutdruckRecordService sgBlutdruckRecordService;

    // 血糖记录表
    private final ISgGlucoseRecordService sgGlucoseRecordService;

    // 血脂记录表
    private final ISgLipidRecordService sgLipidRecordService;

    // 转诊记录表
    private final ISgTreatmentLogService sgTreatmentLogService;

    // 体质监测表
    private final ISgHealthRecordService sgHealthRecordService;

    // redis工具类
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取健康课堂的类型
     *
     * @return 健康课堂的类型
     */
    @GetMapping("getHealthClassType")
    public Result<List<DictModel>> getHealthClassType() {
        return Result.OK(sysDictService.queryDictItemsByCode("health_type"));
    }

    /**
     * 获取当前登录用户的最后一次测量记录
     *
     * @return 获取当前登录用户的最后一次测量记录
     * @author WangJie
     * @date 2022/11/17 14:13
     */
    @GetMapping("getLastMeasureRecord")
    public Result<Map<String, Object>> getTest(HttpServletRequest req) {
        LoginMember member = toolUtils.getLoginMember(req);
        Map<String, Object> List = new HashMap<>();
        // region 高血压
        QueryWrapper<SgBlutdruckRecord> BlutdruckRecordWrapper = new QueryWrapper<>();
        BlutdruckRecordWrapper.eq("member_id", member.getId()).orderByDesc("measuring_time").last("LIMIT 1");
        SgBlutdruckRecord BlutdruckRecord = sgBlutdruckRecordService.getOne(BlutdruckRecordWrapper);
        if (BlutdruckRecord != null) {
            String value = BlutdruckRecord.getSbpval() + " / " + BlutdruckRecord.getDbpval();
            List.put("BlutdruckRecord", value);
        } else {
            List.put("BlutdruckRecord", "-");
        }
        // endregion
        // region 高血糖
        QueryWrapper<SgGlucoseRecord> GlucoseRecordWrapper = new QueryWrapper<>();
        GlucoseRecordWrapper.eq("member_id", member.getId()).orderByDesc("measuring_time").last("LIMIT 1");
        SgGlucoseRecord GlucoseRecord = sgGlucoseRecordService.getOne(GlucoseRecordWrapper);
        if (GlucoseRecord != null) {
            List.put("GlucoseRecord", GlucoseRecord.getGluval().toString());
        } else {
            List.put("GlucoseRecord", "-");
        }
        // endregion
        // region 高血脂
        QueryWrapper<SgLipidRecord> LipidRecordWrapper = new QueryWrapper<>();
        LipidRecordWrapper.eq("member_id", member.getId()).orderByDesc("measuring_time").last("LIMIT 1");
        SgLipidRecord LipidRecord = sgLipidRecordService.getOne(LipidRecordWrapper);
        if (LipidRecord != null) {
            List.put("LipidRecord", LipidRecord.getTotalCholesterol());
        } else {
            List.put("LipidRecord", "-");
        }
        // endregion

        return Result.OK(List);
    }


    /**
     * 查询当前登录人的转诊记录
     *
     * @author WangJie
     * @date 2022/11/21 9:55
     */
    @ApiOperation(value = "查询当前登录人的转诊记录", notes = "查询当前登录人的转诊记录")
    @GetMapping(value = "/queryByRecord")
    public Result<List<SgTreatmentLog>> queryByRecord(HttpServletRequest req) {
        LoginMember member = toolUtils.getLoginMember(req);
        List<SgTreatmentLog> sgTreatmentLogs = sgTreatmentLogService.queryByRecord(member.getId());
        return Result.OK(sgTreatmentLogs);
    }

    /**
     * 查询用户健康检测最近7次检测记录
     *
     * @param memberId 居民id
     * @return 结果
     */
    @ApiOperation(value = "通过id查询用户健康检测最近14次记录", notes = "通过id查询用户健康检测最近14次记录")
    @GetMapping(value = "/getRecord")
    public Result<Map<String, Object>> getRecord(String memberId, Integer type) {
        int count = 7;
        // PC端查最近14条/小程序查询最近7条
        if (type != null && type == 1) {
            count = 14;
        }
        // 获取血压检测记录
        List<Double> dbpvalList = new ArrayList<>();
        List<Double> sbpvalList = new ArrayList<>();
        List<Integer> hrList = new ArrayList<>();

        QueryWrapper<SgBlutdruckRecord> blutdruckRecordWrapper = new QueryWrapper<>();
        blutdruckRecordWrapper.eq("member_id", memberId).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgBlutdruckRecord> sgBlutdruckRecordList = sgBlutdruckRecordService.list(blutdruckRecordWrapper);
        // 反转集合
        Collections.reverse(sgBlutdruckRecordList);
        for (SgBlutdruckRecord sb : sgBlutdruckRecordList) {
            dbpvalList.add(sb.getDbpval());
            sbpvalList.add(sb.getSbpval());
            hrList.add(sb.getHeartRate());
        }

        // 获取血糖检测记录
        // 凌晨
        List<Double> morningList = new ArrayList<>();
        QueryWrapper<SgGlucoseRecord> glucoseRecordMorningWrapper = new QueryWrapper<>();
        glucoseRecordMorningWrapper.eq("member_id", memberId).eq("phase", 0).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgGlucoseRecord> sgGlucoseRecordMorningList = sgGlucoseRecordService.list(glucoseRecordMorningWrapper);
        // 反转集合
        Collections.reverse(sgGlucoseRecordMorningList);
        for (SgGlucoseRecord sg : sgGlucoseRecordMorningList) {
            morningList.add(sg.getGluval());
        }
        // 饭前
        List<Double> beforeList = new ArrayList<>();
        QueryWrapper<SgGlucoseRecord> glucoseRecordBeforeWrapper = new QueryWrapper<>();
        glucoseRecordBeforeWrapper.eq("member_id", memberId).in("phase", 1, 3, 5).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgGlucoseRecord> sgGlucoseRecordBeforeList = sgGlucoseRecordService.list(glucoseRecordBeforeWrapper);
        // 反转集合
        Collections.reverse(sgGlucoseRecordBeforeList);
        for (SgGlucoseRecord sg : sgGlucoseRecordBeforeList) {
            beforeList.add(sg.getGluval());
        }

        // 饭后
        List<Double> afterList = new ArrayList<>();
        QueryWrapper<SgGlucoseRecord> glucoseRecordAfterWrapper = new QueryWrapper<>();
        glucoseRecordAfterWrapper.eq("member_id", memberId).in("phase", 2, 4, 6).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgGlucoseRecord> sgGlucoseRecordAfterList = sgGlucoseRecordService.list(glucoseRecordAfterWrapper);
        // 反转集合
        Collections.reverse(sgGlucoseRecordAfterList);
        for (SgGlucoseRecord sg : sgGlucoseRecordAfterList) {
            afterList.add(sg.getGluval());
        }

        // 睡前
        List<Double> nightList = new ArrayList<>();
        QueryWrapper<SgGlucoseRecord> glucoseRecordNightWrapper = new QueryWrapper<>();
        glucoseRecordNightWrapper.eq("member_id", memberId).eq("phase", 7).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgGlucoseRecord> sgGlucoseRecordNightList = sgGlucoseRecordService.list(glucoseRecordNightWrapper);
        // 反转集合
        Collections.reverse(sgGlucoseRecordNightList);
        for (SgGlucoseRecord sg : sgGlucoseRecordNightList) {
            nightList.add(sg.getGluval());
        }

        // 获取血脂检测记录
        List<Double> totalCholesterolList = new ArrayList<>();
        List<Double> triglycerideList = new ArrayList<>();
        List<Double> ldlcList = new ArrayList<>();
        List<Double> hdlcList = new ArrayList<>();

        QueryWrapper<SgLipidRecord> sgLipidRecordWrapper = new QueryWrapper<>();
        sgLipidRecordWrapper.eq("member_id", memberId).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgLipidRecord> sgLipidRecordList = sgLipidRecordService.list(sgLipidRecordWrapper);
        // 反转集合
        Collections.reverse(sgLipidRecordList);
        for (SgLipidRecord sl : sgLipidRecordList) {
            totalCholesterolList.add(sl.getTotalCholesterol());
            triglycerideList.add(sl.getTriglyceride());
            ldlcList.add(sl.getLdlc());
            hdlcList.add(sl.getHdlc());
        }

        // 获取体脂检测记录
        List<Double> bmiList = new ArrayList<>();
        List<String> weightList = new ArrayList<>();

        QueryWrapper<SgHealthRecord> healthRecordWrapper = new QueryWrapper<>();
        healthRecordWrapper.eq("member_id", memberId).orderByDesc("measuring_time").last("limit 0," + count);
        List<SgHealthRecord> sgHealthRecordlist = sgHealthRecordService.list(healthRecordWrapper);
        // 反转集合
        Collections.reverse(sgHealthRecordlist);
        for (SgHealthRecord sh : sgHealthRecordlist) {
            bmiList.add(sh.getBmi());
            weightList.add(sh.getWeight());
        }

        // 封装JSON
        Map<String, Object> jsonMap = new HashMap<>();

        // 血压
        Map<String, Object> bpMap = new HashMap<>();
        bpMap.put("dbpval", dbpvalList);
        bpMap.put("sbpval", sbpvalList);
        bpMap.put("hr", hrList);

        jsonMap.put("bp", bpMap);

        // 血糖
        Map<String, Object> bsMap = new HashMap<>();
        bsMap.put("morning", morningList);
        bsMap.put("before", beforeList);
        bsMap.put("after", afterList);
        bsMap.put("night", nightList);

        jsonMap.put("bs", bsMap);

        // 血脂
        Map<String, Object> bfMap = new HashMap<>();
        bfMap.put("totalCholesterol", totalCholesterolList);
        bfMap.put("triglyceride", triglycerideList);
        bfMap.put("ldlc", ldlcList);
        bfMap.put("hdlc", hdlcList);

        jsonMap.put("bf", bfMap);

        // 体脂
        Map<String, Object> btMap = new HashMap<>();
        btMap.put("bmi", bmiList);
        btMap.put("weight", weightList);

        jsonMap.put("bt", btMap);

        return Result.OK(jsonMap);
    }

    @ApiOperation(value = "最后一次检测记录", notes = "最后一次检测记录index:0血压，1血糖，2血脂，3体脂,不传查全部&mid:居民id")
    @GetMapping("/getTestLastTime")
    public Result<Object> testLastTime(String mid, Integer index) {
        if (index == 0) {
            SgBlutdruckRecord row = sgBlutdruckRecordService.getOne(
                    new QueryWrapper<SgBlutdruckRecord>().eq("member_id", mid)
                            .orderByDesc("measuring_time")
                            .last("LIMIT 1")
                            .select("sbpval", "dbpval", "measuring_time")
            );
            if (row == null) {
                JSONObject object = new JSONObject();
                object.set("sbpval", "-");
                object.set("dbpval", "-");
                object.set("measuringTime", "");
                return Result.OK(object);
            }
            return Result.ok(row);
        } else if (index == 1) {
            SgGlucoseRecord row = sgGlucoseRecordService.getOne(
                    new QueryWrapper<SgGlucoseRecord>().eq("member_id", mid)
                            .orderByDesc("measuring_time")
                            .last("LIMIT 1")
                            .select("gluval", "phase", "measuring_time")
            );
            if (row == null) {
                JSONObject object = new JSONObject();
                object.set("gluval", "-");
                object.set("phase", "");
                object.set("measuringTime", "");
                return Result.OK(object);
            }
            return Result.ok(row);
        } else if (index == 2) {
            SgLipidRecord row = sgLipidRecordService.getOne(
                    new QueryWrapper<SgLipidRecord>().eq("member_id", mid)
                            .orderByDesc("measuring_time")
                            .last("LIMIT 1")
                            .select("total_cholesterol", "triglyceride", "ldlc", "hdlc", "measuring_time")
            );
            if (row == null) {
                JSONObject object = new JSONObject();
                object.set("totalCholesterol", "-");
                object.set("triglyceride", "-");
                object.set("ldlc", "-");
                object.set("hdlc", "-");
                object.set("measuringTime", "");
                return Result.OK(object);
            }
            return Result.ok(row);
        } else if (index == 3) {
            SgHealthRecord row = sgHealthRecordService.getOne(
                    new QueryWrapper<SgHealthRecord>().eq("member_id", mid)
                            .orderByDesc("measuring_time")
                            .last("LIMIT 1")
                            .select("bmi", "weight", "measuring_time")
            );
            if (row == null) {
                JSONObject object = new JSONObject();
                object.set("bmi", "-");
                object.set("weight", "-");
                object.set("measuringTime", "");
                return Result.OK(object);
            }
            return Result.ok(row);
        }
        return Result.error("");
    }

    @ApiOperation(value = "小程序检测记录", notes = "小程序检测记录 index：0血压，1血糖，2血脂，3体脂,不传查全部&mid:居民id")
    @GetMapping("/queryPageList")
    public Result<Object> queryPageList(String mid,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        Integer index) {
        if (index == 0) {
            Page<SgBlutdruckRecord> page = new Page<>(pageNo, pageSize);
            IPage<SgBlutdruckRecord> pageList = sgBlutdruckRecordService.page(page, new QueryWrapper<SgBlutdruckRecord>().eq("member_id", mid)
                    .select("id", "measuring_time", "sbpval", "dbpval", "heart_rate", "intervene").orderByDesc("measuring_time"));
            return Result.OK(pageList);
        } else if (index == 1) {
            Page<SgGlucoseRecord> page = new Page<>(pageNo, pageSize);
            IPage<SgGlucoseRecord> pageList = sgGlucoseRecordService.page(page, new QueryWrapper<SgGlucoseRecord>().eq("member_id", mid)
                    .select("id", "measuring_time", "gluval", "phase", "level").orderByDesc("measuring_time"));
            return Result.OK(pageList);
        } else if (index == 2) {
            Page<SgLipidRecord> page = new Page<>(pageNo, pageSize);
            IPage<SgLipidRecord> pageList = sgLipidRecordService.page(page, new QueryWrapper<SgLipidRecord>().eq("member_id", mid)
                    .select("id", "measuring_time", "total_cholesterol", "triglyceride", "ldlc", "hdlc").orderByDesc("measuring_time"));
            return Result.OK(pageList);
        } else if (index == 3) {
            Page<SgHealthRecord> page = new Page<>(pageNo, pageSize);
            IPage<SgHealthRecord> pageList = sgHealthRecordService.page(page, new QueryWrapper<SgHealthRecord>().eq("member_id", mid)
                    .select("id", "measuring_time", "weight", "bmi", "level").orderByDesc("measuring_time"));
            return Result.OK(pageList);
        }
        return Result.ok();
    }

    /**
     * TODO     小程序接口-centreOne-/高血压/高血糖/高血脂
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/17 13:33
     * @Exception
     */
    @ApiOperation(value = "小程序接口-centreOne-高血压人数/高血糖人数/高血脂人数", notes = "小程序接口-centreOne-高血压人数/高血糖人数/高血脂人数")
    @GetMapping(value = "/personnelWordTo")
    public Result<Map<String, Object>> personnelWordTo() {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            // 获取当前登录用户的角色
            String roleCode = redisUtil.get("roleCode:" + user.getId()).toString();
            Map<String, Object> list = new HashMap<>();
            List<Map<String, Object>> data = new ArrayList<>();
            Map<String, Object> item = new HashMap<>();

            // 血压
            QueryWrapper<SgMember> memberQueryWrapperBlutdruck = new QueryWrapper<>();
            // 血糖
            QueryWrapper<SgMember> memberQueryWrapperGlucose = new QueryWrapper<>();
            // 血脂
            QueryWrapper<SgMember> memberQueryWrapperLipid = new QueryWrapper<>();


            memberQueryWrapperBlutdruck
                    .like("three_tag", 0)
                    .eq("del_flag", 0);
            memberQueryWrapperGlucose
                    .like("three_tag", 1)
                    .eq("del_flag", 0);
            memberQueryWrapperLipid
                    .like("three_tag", 2)
                    .eq("del_flag", 0);

            if (roleCode.contains("dept_manage")) {
                // 机构管理员，查询的是本机构下的数据
                memberQueryWrapperBlutdruck.like("sys_org_code", user.getOrgCode());
                memberQueryWrapperGlucose.like("sys_org_code", user.getOrgCode());
                memberQueryWrapperLipid.like("sys_org_code", user.getOrgCode());
            } else if (!roleCode.contains("admin") && !roleCode.contains("dept_manage")) {
                // 普通医生，只查询自己的
                memberQueryWrapperBlutdruck.like("doctor_id", user.getId());
                memberQueryWrapperGlucose.like("doctor_id", user.getId());
                memberQueryWrapperLipid.like("doctor_id", user.getId());
            }
            list.put("blutdruck", sgMemberService.list(memberQueryWrapperBlutdruck));
            list.put("glucose", sgMemberService.list(memberQueryWrapperGlucose));
            list.put("lipid", sgMemberService.list(memberQueryWrapperLipid));
            return Result.OK(list);
        } catch (Exception e) {
            return Result.error("查询大屏标题/高血压人数/高血糖人数/高血脂人数异常,原因{}" + e.getMessage());
        }
    }
}
